package com.xxl.job.executor.service.thread;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.executor.service.WalletDebitService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 钱包代扣
 */
@Slf4j
public class WalletBatchDebitThread implements Runnable {

    private WalletDebitService walletDebitService;

    private List<String> custNos;

    private CountDownLatch countDown;

    public WalletBatchDebitThread(WalletDebitService walletDebitService, List<String> custNos, CountDownLatch countDown) {
        this.walletDebitService = walletDebitService;
        this.custNos = custNos;
        this.countDown = countDown;
    }

    @Override
    public void run() {
        try {
            custNos.stream().forEach(custNo -> {
                log.debug("countDown remain = {}", this.countDown.getCount());
                try {
                    walletDebitService.walletDebit(custNo);
                } catch (Exception e) {
                    if (e instanceof InterruptedException) {
                        XxlJobHelper.log("任务响应中断请求，停止执行");
                        throw e;
                    }
                    log.error("[钱包代扣 {}] 异常，walletDebit error：{}，", custNo, e.getMessage(), e);
                } finally {
                    countDown.countDown();
                }

                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        } catch (Exception e) {
            if (e instanceof InterruptedException) {
                XxlJobHelper.log("任务响应中断请求，停止执行");
                throw e;
            }
        } finally {
            custNos.clear();
        }

    }

}
